//
//  LYLoginViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/20.s//

import UIKit

class LYLoginViewController: LYBaseViewController {
    
    // MARK: - UI Elements
    lazy var phoneNumberTitleView: LYTitleView = {
        let titleView = LYTitleView()
        titleView.title = LYlocalizedString("Phone Number") 
        titleView.backgroundImage = UIImage(named: "textfield_tip")
        return titleView
    }()
    
    lazy var verificationCodeTitleView: LYTitleView = {
        let titleView = LYTitleView()
        titleView.title = LYlocalizedString("Verification Code")
        titleView.backgroundImage = UIImage(named: "textfield_tip")
        return titleView
    }()
    
    private let phoneNumberField = LYTextField(backgroundImage: UIImage(named: "textfield_num"))
    
    private let verificationCodeField = LYTextField(backgroundImage: UIImage(named: "textfield_num"))
    
    private lazy var getCodeButton: UIButton = {
        let button = UIButton(type: .system)
        // 创建带下划线的属性字符串
        button.setAttributedTitle(getAttributeTitle(LYlocalizedString("Code")),
                                  for: .normal)
        button.addTarget(self, action: #selector(getCodeButtonTapped), for: .touchUpInside)
        button.isHidden = false
        return button
    }()
    
    private lazy var countDownLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.textColor = UIColor(hex: "#999999")
        label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        label.isHidden = true
        return label
    }()
    
    func getAttributeTitle(_ title: String?) -> NSAttributedString? {
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 14, weight: .medium),
            .foregroundColor: UIColor.systemBlue,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]
        
        let attributedTitle = NSAttributedString(
            string: LYlocalizedString("Code"),
            attributes: attributes
        )
        return attributedTitle
    }
    
    private lazy var loginButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle(LYlocalizedString("Login"), for: .normal)
        button.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        button.layer.masksToBounds = true
        button.layer.borderColor = UIColor(hex: "#FFFFFF").cgColor
        button.backgroundColor = UIColor(hex: "#1E4FF3")
        button.layer.borderWidth = 1.0
        button.layer.cornerRadius = 22.5
        button.addTarget(self, action: #selector(loginButtonTapped), for: .touchUpInside)
        return button
    }()
    
    let agreementView = LYAgreementView()
    
    // MARK: - Properties
    private var countdownTimer: Timer?
    private let timerDuration = 60
    private var remainingSeconds = 0
    private let countdownKey = "verificationCodeCountdownExpiry"
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.bgImage = UIImage(named: "background_login")
        self.remainingSeconds = timerDuration
        setupUI()
        setupConstraints()
        configurePhoneNumberField()
        checkSavedCountdown()
        
        if LYUserDefaults.shared.getBool(forKey: loginGoogleMarketKey) == nil
        {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                LYIDFAManager.shared.requestTrackingAuthorization { idfa in
                    // google_market上报
                    LYTrackingManager.uploadGoogleMarketTracking()
                    LYUserDefaults.shared.setBool(true, forKey: loginGoogleMarketKey)
                }
            }
        }

        LYUserDefaults.shared.setDouble(Date().timeIntervalSince1970, forKey: loginStartTimeKey)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        countdownTimer?.invalidate()
    }
    
    // MARK: - Setup
    private func setupUI() {
        view.backgroundColor = .white
        
        // Configure input fields
        phoneNumberField.placeholder = LYlocalizedString("Enter phone number")
        phoneNumberField.keyboardType = .numberPad
        phoneNumberField.maxLength = 10
        phoneNumberField.textField.text = LYUserDefaults.shared.getString(forKey: phoneNumKey)
        verificationCodeField.placeholder = LYlocalizedString("Enter verification code")
        verificationCodeField.keyboardType = .numberPad
        verificationCodeField.maxLength = 6
        
        agreementView.onAgreementTapped = { [weak self] in
            guard let self = self else { return }
            let url = APIDomain.h5.rawValue + "/hangry"
            self.pushToWebViewController(url)
        }
        
        // Add subviews
        view.addSubview(phoneNumberTitleView)
        view.addSubview(phoneNumberField)
        view.addSubview(verificationCodeTitleView)
        view.addSubview(verificationCodeField)
        view.addSubview(getCodeButton)
        view.addSubview(countDownLabel)
        view.addSubview(loginButton)
        view.addSubview(agreementView)
    }
    
    private func configurePhoneNumberField() {
        // Create prefix view with +86 and separator
        let prefixView = UIView()
        let countryCodeLabel = UILabel()
        countryCodeLabel.text = "+" + appCountryEnv.numberCode
        countryCodeLabel.font = UIFont.systemFont(ofSize: 16)
        countryCodeLabel.textColor = .darkGray
        
        let separator = UIView()
        separator.backgroundColor = .lightGray
        separator.snp.makeConstraints { make in
            make.width.equalTo(1)
        }
        
        let stackView = UIStackView(arrangedSubviews: [countryCodeLabel, separator])
        stackView.axis = .horizontal
        stackView.spacing = 8
        stackView.alignment = .center
        
        prefixView.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8))
        }
        
        separator.snp.makeConstraints { make in
            make.height.equalTo(20)
        }
        
        phoneNumberField.setLeftView(view: stackView, width: 60)
        phoneNumberField.textField.delegate = self
    }
    
    private func setupConstraints() {
        
        phoneNumberTitleView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(266)
            make.leading.trailing.equalToSuperview().inset(20)
        }
        
        phoneNumberField.snp.makeConstraints { make in
            make.top.equalTo(phoneNumberTitleView.snp.bottom)
            make.leading.trailing.equalToSuperview().inset(20)
            make.height.equalTo(45)
        }
        
        verificationCodeTitleView.snp.makeConstraints { make in
            make.top.equalTo(phoneNumberField.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview().inset(20)
        }
        
        verificationCodeField.snp.makeConstraints { make in
            make.top.equalTo(verificationCodeTitleView.snp.bottom)
            make.leading.trailing.equalTo(phoneNumberField)
            make.height.equalTo(45)
        }
        
        getCodeButton.snp.makeConstraints { make in
            make.centerY.equalTo(verificationCodeField)
            make.trailing.equalTo(verificationCodeTitleView).offset(-10)
        }
        
        countDownLabel.snp.makeConstraints { make in
            make.edges.equalTo(getCodeButton)
        }
        
        loginButton.snp.makeConstraints { make in
            make.top.equalTo(verificationCodeField.snp.bottom).offset(40)
            make.leading.trailing.equalToSuperview().inset(20)
            make.height.equalTo(55)
        }
        
        agreementView.snp.makeConstraints { make in
            make.height.equalTo(47)
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-bottomMargin - 10)
        }
    }
    
    // MARK: - Countdown Logic
    private func checkSavedCountdown() {
        guard let expiryDate = LYUserDefaults.shared.getObject(forKey: countdownKey, type: Date.self) else {
            return
        }
        
        let remaining = Int(expiryDate.timeIntervalSinceNow)
        if remaining > 0 {
            remainingSeconds = remaining
            startCountdown()
        }
    }
    
    private func saveCountdownExpiry() {
        let expiryDate = Date().addingTimeInterval(TimeInterval(remainingSeconds))
        LYUserDefaults.shared.set(expiryDate, forKey: countdownKey)
    }
    
    @objc func startCountdown() {
        removeTimer()
        updateCodeButtonState()
        
        countdownTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            self.remainingSeconds -= 1
            self.updateCodeButtonState()
            
            if self.remainingSeconds <= 0 {
                removeTimer()
                LYUserDefaults.shared.remove(forKey: countdownKey)
            } else {
                self.saveCountdownExpiry()
            }
        }
        RunLoop.current.add(countdownTimer!, forMode: .common)
    }
    
    func removeTimer() {
        countdownTimer?.invalidate()
        countdownTimer = nil
        remainingSeconds = timerDuration
    }
    
    private func updateCodeButtonState() {
        if remainingSeconds > 0 {
            getCodeButton.isHidden = true
            countDownLabel.isHidden = false
            countDownLabel.text = LYlocalizedString("\(remainingSeconds)s")
        } else {
            getCodeButton.isHidden = false
            countDownLabel.isHidden = true
        }
    }
    
    @objc private func getCodeButtonTapped() {
        guard let phone = phoneNumberField.textField.text?.trimmingCharacters(in: .whitespaces),
              !phone.isEmpty else {
            LYHUDUtils.showToast("Please enter phone number first")
            return
        }
        fetchVerficationCode(phone)
    }
    
    func fetchVerficationCode(_ phone: String) {
        LYHUDUtils.showLoading()
        LYStocksManager.fetchVerificationCode(phoneNumber: phone) { [weak self] verificationCodeModel, msg, error in
            guard let self = self else { return }
            if error == nil {
                self.startCountdown()
                LYHUDUtils.hideHUD()
            }
            LYHUDUtils.showToast(msg)
        }
    }
    
    // MARK: - Login Logic
    @objc private func loginButtonTapped() {
        self.view.endEditing(true)
//        guard let phoneNumber = phoneNumberField.textField.text, !phoneNumber.isEmpty else {
//            LYHUDUtils.showToast(LYlocalizedString("Please enter phone number"))
//            return
//        }
        
        guard let verificationCode = verificationCodeField.textField.text, !verificationCode.isEmpty else {
            LYHUDUtils.showToast(LYlocalizedString("Please enter verification code"))
            return
        }
        
        guard agreementView.isSelected else {
            LYHUDUtils.showToast(LYlocalizedString("aggree privacy"))
            return
        }
        
        LYHUDUtils.showLoading()
        LYStocksManager.fetchLogin(phoneNumber: phoneNumberField.textField.text ?? "", code: verificationCode) { [weak self] loginModel, msg, error in
            guard let self = self else { return }
            if error == nil {
                dismiss()
                LYUserDefaults.shared.setDouble(Date().timeIntervalSince1970, forKey: loginEndTimeKey)
                LYHUDUtils.hideHUD()
            } else {
                
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    private func showAlert(message: String) {
        let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
    
    func dismiss() {
        guard let window = UIApplication.shared.currentKeyWindow else { return }
        
        if window.rootViewController is LYNavigationController {
            self.dismiss(animated: true)
        } else {
            let mainVC = LYMainViewController()
            
            UIView.transition(with: window,
                              duration: 0.3,
                              options: .transitionCrossDissolve,
                              animations: {
                window.rootViewController = mainVC
            }, completion: { _ in
                window.makeKeyAndVisible()
                DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
                    LYLocationManager.shared.requestLocationPermission(nil)
                }
            })
        }
    }
    
    func pushToWebViewController(_ url: String) {
        let webviewVC = LYWebViewController()
        webviewVC.urlString = url
        webviewVC.isPresent = true
        let nav = LYNavigationController(rootViewController: webviewVC)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true)
    }
}

// MARK: - UITextFieldDelegate
extension LYLoginViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == phoneNumberField.textField || textField == verificationCodeField.textField {
            let allowedCharacters = CharacterSet.decimalDigits
            let characterSet = CharacterSet(charactersIn: string)
            return allowedCharacters.isSuperset(of: characterSet)
        }
        return true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
}
